package codeRandomThoughts.Test110平衡二叉树;

import codeRandomThoughts.utils.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 迭代法
 * 我想的这种方法不行
 * 并不是平衡二叉树的充要条件
 */
public class Solution2 {
    public boolean isBalanced(TreeNode root) {
        TreeNode node = root;
        if (node == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(node);
        int depth=0;
        int firstLeafDepth=0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            depth++;
            while (size > 0) {
                node = queue.poll();
                if (node.left==null || node.right==null){
                    //node是叶子节点
                    if (firstLeafDepth==0){
                        firstLeafDepth=depth;
                    }
                    if (depth-firstLeafDepth>1){
                        return false;
                    }
                }

                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
        }
        return true;
    }
}
